﻿using UnityEditor;
using UnityEngine;
using System.Collections;
using UnityEditor.SceneManagement;
using UnityEngine.SceneManagement;

namespace Hont.BlazingNodePackage
{
    [CustomEditor(typeof(BlazingNodeMono), true)]
    public class BlazingNodeMonoInspector : Editor
    {
        UnityEngine.Object mLinkedFile;

        BlazingNodeMono mBlazingNodeMono;

        BlazingNodeMono BlazingNodeMono
        {
            get
            {
                if (mBlazingNodeMono == null)
                {
                    mBlazingNodeMono = base.target as BlazingNodeMono;
                }

                return mBlazingNodeMono;
            }
        }


        public override void OnInspectorGUI()
        {
            if (Application.isPlaying)
            {
                EditorGUILayout.HelpBox("Play Mode You Can`t Edit!", MessageType.Info);
                return;
            }

            EditorGUILayout.BeginHorizontal(GUI.skin.box);
            EditorGUILayout.LabelField("Node File");

            var newLinkedFile = EditorGUILayout.ObjectField(mLinkedFile, typeof(TextAsset), false);

            if (GUILayout.Button("Open", GUILayout.Width(40)))
            {
                if (BlazingNodeEditor_Core.Instance == null)
                    BlazingNodeEditor_Core.Setup();

                if (!string.IsNullOrEmpty(BlazingNodeMono.resourcePath))
                {
                    BlazingNodeEditor_Core.Instance.ForceLoad(BlazingNodeMono.resourcePath);
                    BlazingNodeEditor_Core.Instance.Focus();
                }
            }
            EditorGUILayout.EndHorizontal();

            if (!string.IsNullOrEmpty(BlazingNodeMono.resourcePath))
            {
                var resourceObject = Resources.Load(BlazingNodeMono.resourcePath);
                if (resourceObject == null)
                    EditorGUILayout.HelpBox("Blazing object has not contain in resource folder or not xml!", MessageType.Error);
            }

            if (newLinkedFile != mLinkedFile)
            {
                if (newLinkedFile != null)
                {
                    var resourcePath = AssetDatabase.GetAssetPath(newLinkedFile.GetInstanceID());
                    if (resourcePath.Contains("Resources/"))
                    {
                        var resInx = resourcePath.IndexOf("Resources/") + "Resources/".Length;
                        resourcePath = resourcePath.Substring(resInx);
                        var dotInx = resourcePath.LastIndexOf('.');
                        resourcePath = resourcePath.Substring(0, dotInx);

                        Undo.RecordObject(target, "Blazing_PathChange");
                        BlazingNodeMono.resourcePath = resourcePath;
                        EditorSceneManager.MarkSceneDirty(SceneManager.GetActiveScene());
                    }
                }
                else
                {
                    BlazingNodeMono.resourcePath = "";
                }

                mLinkedFile = newLinkedFile;
            }

            try
            {
                if (!string.IsNullOrEmpty(BlazingNodeMono.resourcePath))
                {
                    mLinkedFile = Resources.Load(BlazingNodeMono.resourcePath);
                }

                if (!BlazingNodeMono.BlazingNode.IsLoaded && !string.IsNullOrEmpty(BlazingNodeMono.resourcePath))
                    BlazingNodeMono.BlazingNode.Load(BlazingNodeMono.resourcePath);
            }
            catch { }

            if (!BlazingNodeMono.BlazingNode.IsLoaded) return;

            GUILayout.Space(3);

            var paramHeight = 20f + 2 * 2f;

            EditorGUI.BeginChangeCheck();
            for (int i = 0; i < BlazingNodeMono.BlazingNode.Document.ParametersList.Count; i++)
            {
                var item = BlazingNodeMono.BlazingNode.Document.ParametersList[i];

                GUILayout.Box("", GUIStyle.none, GUILayout.Height(28));
                var lastRect = GUILayoutUtility.GetLastRect();

                var paramBoundRect = new Rect(lastRect.x, lastRect.y, lastRect.width, paramHeight);

                GUI.Box(paramBoundRect, "", GUI.skin.button);
                var nameAreaRect = paramBoundRect;
                nameAreaRect.width *= 0.5f;
                nameAreaRect.y += 2;
                GUI.Label(nameAreaRect, item.Name);

                var valueRect = nameAreaRect;
                valueRect.x += valueRect.width;
                item.OnDrawFieldGUI(valueRect);
            }

            if (EditorGUI.EndChangeCheck())
                Save();
        }

        void OnDestroy()
        {
            if (mBlazingNodeMono == null) return;

            mBlazingNodeMono.ResetBlazingNode();
            mBlazingNodeMono = null;
        }

        void Save()
        {
            if (mLinkedFile == null) return;

            var po = BlazingNodeHelper.ConvertToDocumentPO(BlazingNodeMono.BlazingNode.Document);
            var persistStr = BlazingNodeHelper.XmlSerialize(po);

            BlazingNodeHelper.WriteAllText(AssetDatabase.GetAssetPath(mLinkedFile), persistStr);
        }
    }
}
